package com.cloudlinkscm.base.filecenter.domain;

import com.cloudlinkscm.base.filecenter.dao.SysAuthCodeDao;
import com.cloudlinkscm.base.filecenter.exception.NotAuthorizedException;
import com.cloudlinkscm.base.filecenter.exception.AuthCodeExpiredException;
import com.cloudlinkscm.base.filecenter.model.SysAuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 系统授权码manager
 *
 * @author : tac
 * @date : 2017/7/24
 */
@Component
public class SysAuthCodeManager {
    public SysAuthCodeDao dao;
    private Map<String, SysAuthCode> auths = new HashMap<>();

    @Autowired
    public SysAuthCodeManager(SysAuthCodeDao dao) {
        this.dao = dao;
    }

    /**
     * 获取指定系统编码对应的系统授权信息，带缓存
     *
     * @exception NotAuthorizedException
     * @exception AuthCodeExpiredException
     */
    public SysAuthCode getOrThrow(String sysCode) throws NotAuthorizedException, AuthCodeExpiredException {
        SysAuthCode auth;
        if(auths.containsKey(sysCode)){
            auth = auths.get(sysCode);
        } else {
            auth = dao.getBySysCode(sysCode);
            if (auth == null) {
                throw new NotAuthorizedException(sysCode);
            } else {
                auths.put(sysCode, auth);
            }
        }
        if(isExpired(auth)){
            throw new AuthCodeExpiredException(sysCode);
        }

        return auth;
    }

    protected boolean isExpired(SysAuthCode auth) {
        if (auth.getExpiredTime() == null) {
            return false;
        }
        return auth.getExpiredTime().compareTo(new Date()) < 0;
    }
}
